package com.theme.passport.service.theme.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.theme.common.mvc.utils.PageUtils;
import com.theme.common.mvc.utils.Query;
import com.theme.passport.dao.theme.AlbumProductDao;
import com.theme.passport.entity.theme.AlbumProductEntity;
import com.theme.passport.service.theme.AlbumProductService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;


@Service("albumProductService")
public class AlbumProductServiceImpl extends ServiceImpl<AlbumProductDao, AlbumProductEntity> implements AlbumProductService {

    @Autowired
    private AlbumProductService albumProductService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        String status = (String) params.get("status");
        String albumId = (String) params.get("albumId");
        IPage<AlbumProductEntity> page = this.page(
                new Query<AlbumProductEntity>().getPage(params),
                new QueryWrapper<AlbumProductEntity>()
                        .eq(StringUtils.isNotBlank(albumId), "album_id", albumId)
                        .in(StringUtils.isNotBlank(status), "status", status)
                        .orderByDesc("created")
        );
        return new PageUtils(page);
    }

    @Override
    public void updateAlbumProduct(List<Long> objectIds, Long albumId) {
        //1、删除以及存在的
        Wrapper<AlbumProductEntity> queryWrapper = new QueryWrapper<AlbumProductEntity>()
                .eq("album_id", albumId);
        List<AlbumProductEntity> alreadyList = albumProductService.list(queryWrapper);

        List<Long> recommendIds = new ArrayList<>(10);
        alreadyList.forEach(item ->{
            recommendIds.add(item.getId());
        });
        albumProductService.removeByIds(recommendIds);
        //2、新增新的列表
        List<AlbumProductEntity> newList = new ArrayList<>(10);
        objectIds.forEach(objectId ->{
            AlbumProductEntity recommend = new AlbumProductEntity();
            recommend.setAlbumId(albumId);
            recommend.setObjectId(objectId);
            recommend.setCreated(new Date());
            recommend.setUpdated(new Date());
            newList.add(recommend);
        });
        albumProductService.saveBatch(newList);
    }

}